package com.edu.controller;

import com.edu.bean.User;
import com.edu.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @Author:何包蛋
 * @Date :2022/12/7 - 12 - 07 - 18:16
 */
@Controller
@SessionAttributes(value = "user")
public class UserController {

    @Resource
    private UserService userService;

    @RequestMapping("/register")
    public String register(String userName , String password , MultipartFile myFile, Model model) throws IOException {
        User user = null;
        if (!myFile.isEmpty()){
            String str = myFile.getContentType();
            String type = str.substring(0,str.indexOf("/"));
            if (type.equals("image")){
                String realPath = "E:\\imgs";
                File folder =  new File(realPath);
                if (!folder.exists()){
                    folder.mkdirs();
                }
                String headUrl = System.currentTimeMillis()+myFile.getOriginalFilename().substring(myFile.getOriginalFilename().indexOf("."));
                File desFile = new File(realPath,headUrl);
                myFile.transferTo(desFile);
                user = new User(userName,password,headUrl);

            }else{
                model.addAttribute("msg","上传头像类型不合");
                return "register.jsp";
            }
        }else{
            user = new User(userName,password,"default.jpg");
        }
        int i = userService.addUser(user);
        if (i == 1){
            model.addAttribute("msg","注册用户成功");
        } else if (i == 0) {
            model.addAttribute("msg","注册用户失败");
        } else if (i == -1) {
            model.addAttribute("msg","用户名已存在");
        }
        return "register.jsp";
    }

    @RequestMapping("/login")
    public String login(User user,Model model){
        User user1 = userService.getUserByName(user.getUserName());
        if (user1!=null){
            if (user1.getPassword().equals(user.getPassword())){
                model.addAttribute("user",user1);
                return "user.jsp";
            }else{
                model.addAttribute("msg","密码错误");
                return "login.jsp";
            }
        }else {
            model.addAttribute("msg","用户名不存在");
            return "login.jsp";

        }

    }

}
